import { useAppStore } from '@/pinia/app';
import { type InitWxDramaPlayInfo, addChasingDramaAxios, addWatchDramaAxios, cancelChasingDramaAxios, initWxDramaPlayInfoAxios } from '@/api/drama';
import { wechatCreateBalanceOrderAxios } from '@/api/pay';
import { isObject } from '@/mxp-ui/mxp-tool/utils/verify';
import { getAppInfo } from '@/config/mp-config';
import { autoLogin } from '@/utils/page/user';
import { RewardedVideoAd } from '@/utils/page/adUtil';
import type { WxMpConfig } from '@/config/mp/wx';
import { nextTick } from 'vue';
import { userActionLog } from '@/api/datapoint';

const plugin = requirePlugin('playlet-plugin');
export class WxPlayletManager {
  public plugin: WXPlaylet.PlayletPlugin = requirePlugin('playlet-plugin');
  public managerInstance: WXPlaylet.PlayletManagerInstance | undefined = undefined;
  public appStore = useAppStore();
  /** 短剧组件内部初始化回调 */
  public async onPlayerLoad(info: WXPlaylet.OnPageLoadParam) {
    try {
      this.managerInstance = plugin.PlayletManager.getPageManager(info.playerId);
      const launchQuery = isObject(this.appStore.launchQuery) ? this.appStore.launchQuery : {};
      this.appStore.setToDramaPageTime(Date.now());
      console.log('==================>info', info);
      this.appStore.setLaunchQuery({
        ...launchQuery,
        ...info,
        channelId: info.channelId || launchQuery.channelId,
        referralLinkId: info.referralLinkId || launchQuery.referralLinkId,
        clickid: info.clickid || launchQuery.clickid,
        projectid: info.project_id || launchQuery.projectid,
        promotionid: info.promotion_id || launchQuery.promotionid,
        wxFinderId: info.wxFinderId || launchQuery.wxFinderId,
        wxExportId: info.wxExportId || launchQuery.wxExportId,
        wxPromotionId: info.wxPromotionId || launchQuery.wxPromotionId,
      });

      this.appStore.setWxPlayletCharge({ playerId: info.playerId, rewardedVideoAd: undefined });
      const res: InitWxDramaPlayInfo = await this.initPlayInfo(info.dramaId); // 得到可播放剧集信息
      // 注册广告解锁并设置
      this.appStore.setWxPlayletCharge({ playerId: info.playerId, rewardedVideoAd: this.useAd() });
      this.appStore.updateIsIaaFlag(res.isIaaFlag);
      // 设置可播放剧集
      this.managerInstance!.setCanPlaySerialList({ data: res.encryptedData, freeList: res.freeList }); // 设置可播放剧集
      // 添加观看记录
      this.appStore.loginState && addWatchDramaAxios({ thirdDramaId: info.dramaId, episodeSeq: info.serialNo });
      // 监听需要解锁的事件
      this.managerInstance?.onCheckIsCanPlay(this.onCheckIsCanPlay.bind(this));

      // 播放器内相关事件的回调函数
      this.managerInstance.onDataReport((data) => {
        if (data.event === this.plugin.REPORT_DATA_EVENTS.CHANGE_SERIAL) {
          // 切换剧集添加观看记录
          this.appStore.loginState && addWatchDramaAxios({ thirdDramaId: data.dramaId!, episodeSeq: Number(data.serialNo) });
        }
        if (data.event === this.plugin.REPORT_DATA_EVENTS.FAV) {
          // 追剧
          addChasingDramaAxios({ thirdDramaId: info.dramaId });
        }
        if (data.event === this.plugin.REPORT_DATA_EVENTS.UNFAV) {
          // 取消追剧
          cancelChasingDramaAxios({ thirdDramaId: info.dramaId });
        }

        if (data.event === this.plugin.REPORT_DATA_EVENTS.WATCH_TIME) {
          //观看时长
          userActionLog({
            userId: this.appStore.userInfo?.userId,
            data: JSON.stringify(data),
            eventType: 'AI_WX_WATCH_TIME',
            msg: '',
          });
        }
        if (data.event === this.plugin.REPORT_DATA_EVENTS.CLICK_COMMENT_ENTRY) {
          //点击评论
          userActionLog({
            userId: this.appStore.userInfo?.userId,
            data: JSON.stringify(data),
            eventType: 'AI_WX_WATCH_COMMENT',
            msg: '',
          });
        }
        if (data.event === this.plugin.REPORT_DATA_EVENTS.LIKE) {
          //点赞
          userActionLog({
            userId: this.appStore.userInfo?.userId,
            data: JSON.stringify(data),
            eventType: 'AI_WX_WATCH_LIKE',
            msg: '',
          });
        }
        if (data.event === this.plugin.REPORT_DATA_EVENTS.UNLIKE) {
          //取消点赞
          userActionLog({
            userId: this.appStore.userInfo?.userId,
            data: JSON.stringify(data),
            eventType: 'AI_WX_WATCH_UNLIKE',
            msg: '',
          });
        }
        if (data.event === this.plugin.REPORT_DATA_EVENTS.SHARE) {
          //分享
          userActionLog({
            userId: this.appStore.userInfo?.userId,
            data: JSON.stringify(data),
            eventType: 'AI_WX_WATCH_SHARE',
            msg: '',
          });
        }
      });
    } catch (error) {
      userActionLog({
        userId: this.appStore.userInfo?.userId,
        data: '',
        eventType: 'WX_PLAYLET_INIT',
        msg: JSON.stringify(error),
      });
      console.log('error====', error);
    }
  }

  /**
   * 初始化短剧播放信息
   * @param dramaId - 剧剧目ID
   */
  public async initPlayInfo(dramaId: string): Promise<InitWxDramaPlayInfo> {
    let params = {
      thirdDramaId: dramaId,
      referralLinkId: this.appStore?.launchQuery?.referralLinkId,
      channelId: this.appStore.launchQuery?.channelId || undefined,
      clickid: this.appStore.launchQuery?.clickid || undefined,
      projectId: this.appStore.launchQuery.projectid || undefined,
      promotionId: this.appStore.launchQuery.promotionid || undefined,
      launchQuery: JSON.stringify(this.appStore?.launchQuery || {}),
      wxFinderId: this.appStore.launchQuery.wxFinderId,
    };
    try {
      // 未登录则先登录
      !this.appStore.loginState && (await autoLogin());
      // TODO: 此接口请求后台，返回下面的setCanPlaySerialList接口需要的加密参数
      const res = await initWxDramaPlayInfoAxios(params);
      return Promise.resolve(res.data);
    } catch (error) {
      console.log('error====', error);
      userActionLog({
        userId: this.appStore.userInfo?.userId,
        data: JSON.stringify(params),
        eventType: 'WX_DRAMAPLAY_INIT',
        msg: JSON.stringify(error),
      });
      return Promise.reject(error);
    }
  }

  /** 监听需要解锁的事件 */
  public async onCheckIsCanPlay(option: WXPlaylet.OnCheckIsCanPlayEvent) {
    let params = { dramaId: option.dramaId, serialNo: Number(option.serialNo!) };

    if (this.appStore.userInfo?.isAutoPay) {
      try {
        await this.unlock(params);
      } catch (error) {
        console.log('error====', error);
        userActionLog({
          userId: this.appStore.userInfo?.userId,
          data: JSON.stringify(params),
          eventType: 'WX_ONCHECKISCANPLAY',
          msg: JSON.stringify(error),
        });
      }
    } else {
      this.managerInstance?.isCanPlay({ serialNo: Number(option.serialNo), useLastStatus: true });
      // this.openPopup();
    }
  }

  /** 余额解锁 */
  public async unlock(data: { dramaId: string; serialNo: number }) {
    let params = {
      thirdDramaId: data.dramaId,
      episodeSeq: data.serialNo,
      referralLinkId: this.appStore?.launchQuery?.referralLinkId,
      wxFinderId: this.appStore?.launchQuery?.wxFinderId,
    };
    try {
      const res = await wechatCreateBalanceOrderAxios(params);

      this.appStore.updateVirtualCoins(res.data.virtualCoins);
      if (res.data.unLockStatus === 1) {
        this.managerInstance?.isCanPlay({ data: res.data.encryptedData!, serialNo: Number(data.serialNo), useLastStatus: false });
        uni.showToast({ title: res.data.unlockMsg, icon: 'none', position: 'bottom' });
      } else {
        this.managerInstance?.isCanPlay({ serialNo: Number(data.serialNo), useLastStatus: true });
        this.openPopup();
      }
    } catch (error) {
      this.managerInstance?.isCanPlay({ serialNo: Number(data.serialNo), useLastStatus: true });
      uni.showToast({ title: '解锁失败', icon: 'fail', position: 'bottom' });
      console.log('error====', error);
      userActionLog({
        userId: this.appStore.userInfo?.userId,
        data: JSON.stringify(params),
        eventType: 'WX_BALANCE_UNLOCK',
        msg: JSON.stringify(error),
      });
    }
  }

  /**
   * 通过是否为 AII 判断 显示广告解锁弹出框,还是支付弹出框
   */
  public openPopup() {
    if (this.appStore.isIaaFlag === 1) {
      this.managerInstance?.updateOpenArea({ showLeft: false });
      nextTick(() => {
        /** 通知 area-left 页面已经显示 */
        this.managerInstance?.emitCustomEvent('show-area-left', { type: 1 });
      });
    } else {
      this.managerInstance?.showChargeDialog();
    }
  }

  /** 注册广告解锁 */
  public useAd() {
    const appinfo = getAppInfo() as WxMpConfig | undefined;
    const adUnitId = appinfo?.adUnitId || '';
    return new RewardedVideoAd({
      adUnitId,
      /** 广告关闭回调 */
      adCloseCallback: (data) => {
        uni.hideLoading();
        this.managerInstance?.emitCustomEvent('adClose', data);
      },
    });
  }
}
